//
//  GameWebViewController.swift
//  kz
//
//  Created by Tech_001 on 18/8/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//

import Foundation
import UIKit
//import FWPopupView
import JavaScriptCore
class GameWebViewController: GameWebViewBaseController, UIWebViewDelegate{
    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var exitFullScreenTopConstraint: NSLayoutConstraint!
    @IBOutlet weak var exitFullScreenButton: UIButton!
    var url: String?
    var gpid: String?
    var moreBarBtn:UIBarButtonItem?
    var isBack : Bool = false
    var popupView :MXPopupView?
    var _loadView: UIView?
    var _effecView: UIView?
    var gameAlertView: GameAlertView?
    var selectGameDict :[String:Any]?
    var outplaformDic = [String:Any]()
    var jsContext: JSContext!
     var isLoad :Bool = false
    // 如果需要拦截系统返回按钮就重写该方法返回 false
    @objc override func currentViewControllerShouldPop() -> Bool {
        ToolHelper.statisticsPage(pageName:"h5页面-顶部功能-返回")
            if isBack == false {
                let dialogMessage = UIAlertController(title: "提示", message: "确认离开当前游戏?", preferredStyle: .alert)
                dialogMessage.view.tintColor = UIColor.black
                
                let ok = UIAlertAction(title: "确定", style: .default, handler: { (action) -> Void in
                    //popVC = false
                     ToolHelper.statisticsPage(pageName:"顶部功能-返回-确定")
                     self.navigationController?.popViewController(animated: true)
                })
                let cancelExit = UIAlertAction(title: "取消", style: .default, handler: { (action) -> Void in
                     ToolHelper.statisticsPage(pageName:"顶部功能-返回-取消")
                })
                dialogMessage.addAction(ok)
                dialogMessage.addAction(cancelExit)
                
                self.tabBarController?.present(dialogMessage, animated: true, completion: nil)
            }
      
        return isBack
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        print("进入web")
        if self.gpid == "6560923891701" || self.gpid == "1"{
            UserDefaults.standard.set(true, forKey: DefaultKey.IS_WBYZT)
            let resetOrientationTargert = NSNumber(integerLiteral: UIInterfaceOrientation.unknown.rawValue)
            UIDevice.current.setValue(resetOrientationTargert, forKey: "orientation")
            let orientationTarget = NSNumber(integerLiteral: UIInterfaceOrientation.landscapeLeft.rawValue)
            UIDevice.current.setValue(orientationTarget, forKey: "orientation")
        }
        
        self.navigationItem.titleView = UIImageView.init(image: UIImage.init(named: "navi_icon_titleLogo"))
        self.navigationController?.navigationBar.shadowImage = UIImage()
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
        
        self.exitFullScreenButton.isHidden = true
        exitFullScreenTopConstraint.constant = isIphoneX_Series ? 30 : 0
        webView.allowsInlineMediaPlayback = true
        webView.delegate = self
        webView.mediaPlaybackRequiresUserAction = false
        actionReload()
       
        let refreshButton = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(actionReload))
        self.moreBarBtn = UIBarButtonItem(title: "更多", style: .plain, target: self, action: #selector(actionToPopupMoreView))
        refreshButton.tintColor = UIColor.init("333333")
        self.moreBarBtn?.tintColor = UIColor.init("333333")
        self.navigationItem.rightBarButtonItems = [refreshButton,self.moreBarBtn!]
        let time:TimeInterval = 60.0
        DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + time) {
            print("执行123")
            //N 秒后执行想要的操作
            if self._loadView != nil {
                print("执行11123")
                self._loadView?.removeFromSuperview()
            }
        }
       
        //感知设备方向 - 开启监听设备方向
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        //添加通知，监听设备方向改变
        NotificationCenter.default.addObserver(self, selector: #selector(GameWebViewController.receivedRotation), name: UIDevice.orientationDidChangeNotification, object: nil)
        //监听是否全屏
        NotificationCenter.default.addObserver(self, selector: #selector(changeFullScreen), name: NSNotification.Name(rawValue:"IsChangeFullScreen"), object: nil)
    }
    
    @objc func changeFullScreen(notification : Notification){
        self.actionFullScreen()
    }
    deinit {
        /// 移除通知
        print("~~~~~\( UserDefaults.standard.bool(forKey: DefaultKey.IS_WBYZT))")
        NotificationCenter.default.removeObserver(self)
        self.webView.delegate = nil
        self.webView.loadHTMLString("", baseURL: nil)
      //  self.webView.loadRequest(URLRequest.init(url: URL.init(string: "")!))
        self.webView.stopLoading()
        self.webView.reloadInputViews()
        URLCache.shared.removeAllCachedResponses()

    }
    
    override var shouldAutorotate: Bool{
        return true
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self._loadView?.center = self.view.center
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
         if self.gpid == "6560923891701" || self.gpid == "1"{
             UserDefaults.standard.set(true, forKey: DefaultKey.IS_WBYZT)
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
         UserDefaults.standard.set(false, forKey: DefaultKey.IS_WBYZT)
        self.disappearing = true
        if let tabBar = self.tabBarController as? MainTabBarController {
            tabBar.flipOrientation()
            tabBar.view.layoutSubviews()
        }
    }
    
    override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
        if toInterfaceOrientation.isPortrait {
            exitFullScreenTopConstraint.constant = isIphoneX_Series ? 30 : 0
        }else{
            exitFullScreenTopConstraint.constant = 0
        }
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        var logouturl = webView.request!.url!.absoluteString
        if(logouturl.contains("logout")){
          self.navigationController?.popViewController(animated: true)
        }
        
        if self._loadView != nil {
            self._loadView?.removeFromSuperview()
        }
        self._loadView = UIHelper.initLoadView(self)
        self.view.addSubview(self._loadView!)
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        if self._loadView != nil {
            self._loadView?.removeFromSuperview()
        }
         self.jsContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
          let model = SwiftJavaScriptModel()
        self.jsContext.setObject(model, forKeyedSubscript: "ios" as NSCopying & NSObjectProtocol)
        UserDefaults.standard.set(0, forKey: "WebKitCacheModelPreferenceKey")
        UserDefaults.standard.set(false, forKey: "WebKitDiskImageCacheEnabled")
        UserDefaults.standard.set(false, forKey: "WebKitOfflineWebApplicationCacheEnabled")
        UserDefaults.standard.synchronize()
    }

    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        print("网络错误!")
        if self._loadView != nil {
            self._loadView?.removeFromSuperview()
        }
    }
    @IBAction func actionExitFullScreen(_ sender: Any) {
        ToolHelper.statisticsPage(pageName:"全屏-取消全屏")
         self.exitFullScreenButton.isHidden = true
        view.bringSubviewToFront(exitFullScreenButton)
        let keywindow = UIApplication.shared.keyWindow
       
        self.navigationController?.setNavigationBarHidden(false, animated: true)
          UIApplication.shared.setStatusBarHidden(false, with: .slide)
    }
    func actionClosePage(){
        let dialogMessage = UIAlertController(title: "提示", message: "确认离开当前游戏?", preferredStyle: .alert)
        dialogMessage.view.tintColor = UIColor.black
        ToolHelper.statisticsPage(pageName:"顶部功能-更多-关闭")
        let ok = UIAlertAction(title: "确定", style: .default, handler: { (action) -> Void in
            // ToolHelper.statisticsPage(pageName:"顶部功能-关闭-确定")
            self.navigationController?.popViewController(animated: true)
        })
        let cancelExit = UIAlertAction(title: "取消", style: .default, handler: { (action) -> Void in
          //   ToolHelper.statisticsPage(pageName:"顶部功能-关闭-取消")
        })
        dialogMessage.addAction(ok)
        dialogMessage.addAction(cancelExit)
        self.tabBarController?.present(dialogMessage, animated: true, completion: nil)
    }
    func actionFullScreen(){
        ToolHelper.statisticsPage(pageName:"顶部功能-更多-全屏")
         self.exitFullScreenButton.isHidden = false
        view.bringSubviewToFront(exitFullScreenButton)
        let keywindow = UIApplication.shared.keyWindow
  
        self.navigationController?.setNavigationBarHidden(true, animated: true)
          UIApplication.shared.setStatusBarHidden(true, with: .fade)
    }
    
    @objc func actionReload(){
          ToolHelper.statisticsPage(pageName:"h5页面-顶部功能-刷新")
       //由mt 2018.6.4 http 改为https
        let domain = UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)
        
        var urlString = "https://\(domain!)\(self.url!)"
        if gpid == "1"{
            urlString = self.url ?? ""
            print("地址:\(urlString)")
        }
    //   urlString = "https://game.manbetlegend.com/1.html"
        print("游戏地址=======:\(urlString)")
        let myURL = URL(string: urlString)
        var myRequest = URLRequest(url: myURL!)
        myRequest.httpShouldHandleCookies = true
        if gpid == "520723134101"{
            webView.dataDetectorTypes = .link
        }
        
          print("\(myURL)")
        webView.loadRequest(myRequest)
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        if gpid == "520723134101"{
            
            if navigationType == .linkClicked {
                //            ifurl let url = request.url {
                //                UIApplication.shared.openURL(url)
                //            }
                return false
            }
        }
        
       

        return true
    }
    @objc func receivedRotation(){
        self.popupView?.closePageView()
    }
    @objc func tickDown(){
    }
    //点击更多
    @objc func actionToPopupMoreView(){
        let app = UIApplication.shared
        if app.statusBarOrientation == UIInterfaceOrientation.portrait || app.statusBarOrientation == UIInterfaceOrientation.portraitUpsideDown{
            print("竖屏")
            if kScreenWidth == 320{
              self.initPopupView(top: kTabBarHeight+15, right: 70,isHorizontalScreen: false)
            }else if isIphoneX_Series{
       
               self.initPopupView(top: kTabBarHeight+5, right: 70,isHorizontalScreen: false)
            }else{
               self.initPopupView(top: kTabBarHeight+15, right: 70,isHorizontalScreen: false)
            }
        }else if app.statusBarOrientation == UIInterfaceOrientation.landscapeLeft || app.statusBarOrientation == UIInterfaceOrientation.landscapeRight{
            print("横屏")
            if kScreenWidth == 320{
                self.initPopupView(top: 52.5, right: 75,isHorizontalScreen: true)
            }else if isIphoneX_Series{
              self.initPopupView(top: 32.5, right: 120,isHorizontalScreen: true)
            }else{
                self.initPopupView(top: 50, right: 75,isHorizontalScreen: true)
            }
        }
    }
    
    func initPopupView(top:CGFloat,right:CGFloat,isHorizontalScreen:Bool) ->Void{
        self.popupView = MXPopupView.init(gameArray: GlobalInfo.platformInfoData, top: top, right: right,isHorizontalScreen:isHorizontalScreen)
        self.popupView?.callClickBlock({ (dict, index) in
            if let dic = GlobalInfo.platformInfoData?[index]{
                let titilePlaform = dic["f_name"] ?? ""
              //  ToolHelper.statisticsPage(pageName:"首页-\(titilePlaform)-\(dict["name"] as? String ?? "")")
                self.outplaformDic = dic
            }
            self._loadView?.removeFromSuperview()
            self.isLoad = true
            self.gameClick(dict: dict)
        })
        self.popupView?.callClickBlock2 { (index) in
            if index == 1001{//全屏
                self.actionFullScreen()
            }else if index == 1002{ //关闭
                self.actionClosePage()
            }else if index == 1003{ //存款
                let vc = DepoistRootVC()
                vc.isCurrentH5Page = false
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }else if index == 1004{ //取款
                _ = MXWebPopupView.init(imgName: "icon_home_qk", typeName: "取款", toPath: "/walletm/withdraw",isHorizontalScreen:isHorizontalScreen)
            }else if index == 1005{ //转帐
                _ =    MXWebPopupView.init(imgName: "icon_home_zz", typeName: "转账", toPath: "/walletm/transfer",isHorizontalScreen:isHorizontalScreen)
            }else if index == 1006{ //注单
                _ =   MXZDPopupView.init(imgName: "icon_home_zd", typeName: "投注记录",vc: self,isHorizontalScreen:isHorizontalScreen)
            }
        }
    }
    
    //游戏跳转
    func gameClick(dict:[String:Any]?){
        self.selectGameDict = dict
        if let app = PlatformApp.getInstance(dict!["gpid"] as! String){
            print("游戏：\(dict)")
            let isRedirect = dict?["iredirect_to_app"] as? Bool ?? false
            if isRedirect == false{
                let isapp = dict?["isapp"] as? Bool ?? false
                if isapp == true { //跳转体育app
                    self.ationWithApp()
                }else{
                    LoginViewController.loginIfNeedController(currentController: self) {
                        self.continueWithGamePlatform(platform: dict)
                    }
                }
            }else{
                let alertTitle  = dict?["name"] as? String ?? ""
                self._effecView = UIHelper.showBlurEffect(isClick:true)
                self.view.addSubview(_effecView!)
                let alert = GameAlertView.init(title: "\(alertTitle)提示")
                self.gameAlertView = alert
                alert.closeBtn?.addTarget(self, action: #selector(ationWithClose), for: .touchUpInside)
                alert.htmlBtn?.addTarget(self, action: #selector(ationWithHTML), for:.touchUpInside)
                alert.html5Btn?.addTarget(self, action: #selector(ationWithHTML), for:.touchUpInside)
                alert.appBtn?.addTarget(self, action: #selector(ationWithApp), for:.touchUpInside)
                alert.appsBtn?.addTarget(self, action: #selector(ationWithApp), for:.touchUpInside)
                alert.show(target: self, animated: true)
            }
        }else{
            let isapp = dict?["isapp"] as? Bool ?? false
            if isapp == true { //跳转体育app
                self.ationWithApp()
            }else{
                LoginViewController.loginIfNeedController(currentController: self) {
                    self.continueWithGamePlatform(platform: dict)
                }
            }
        }
    }
    
    @objc func ationWithClose(){
        self.gameAlertView?.didTappedOnBackgroundView()
    }
    
    @objc func ationWithHTML(){
        self.continueWithGamePlatform(platform: selectGameDict)
    }
    @objc func ationWithApp(){
        self._effecView?.removeFromSuperview()
        self.gameAlertView?.dismiss(animated: true)
        func callback(_ app: PlatformAppProtocol) {
            if UIApplication.shared.canOpenURL(app.url!){
                self._loadView?.removeFromSuperview()
                let isOpen = UIApplication.shared.openURL(app.url!)
                if isOpen == false{
                    UIHelper.alertSimpleMessage(about: "请检查体育APP是否添加信任描述文件.", withDescription: "")
                }
            } else {
                if let gameInfoData = GlobalInfo.gameInfoData {
                    if let downloadInfo = gameInfoData[app.downloadParam] as? [String: Any]{
                        if let iosDLString = downloadInfo["ios"] as? String {
                            let clientMessage = app.name.uppercased() + " 客户端"
                            let dialogMessage = UIAlertController(title: "娱乐提示", message: "是否下载 \(clientMessage)", preferredStyle: .alert)
                            dialogMessage.view.tintColor = UIColor.black
                            let ok = UIAlertAction(title: "前往下载", style: .default, handler: { (action) -> Void in
                                if let url = URL(string: iosDLString) {
                                    UIApplication.shared.openURL(url)
                                }else{
                                    DispatchQueue.main.async {
                                        
                                        UIHelper.alertSimpleMessage(about: "无法前往下载链接", withDescription: "")
                                    }
                                }
                            })
                            
                            let cancelEnter = UIAlertAction(title: "忽略，直接进入游戏", style: .default, handler: { (action) -> Void in
                                self.toGamePage(dict: self.selectGameDict) //进入h5
                            })
                            let cancelExit = UIAlertAction(title: "取消", style: .default, handler: { (action) -> Void in
                            })
                            
                            dialogMessage.addAction(ok)
                            dialogMessage.addAction(cancelExit)
                            
                            self.tabBarController?.present(dialogMessage, animated: true, completion: nil)
                        } else {
                            DispatchQueue.main.async {
                                
                            }
                            UIHelper.alertSimpleMessage(about: "无法取得下载链接", withDescription: "")
                        }
                    } else {
                        
                        UIHelper.alertSimpleMessage(about: "无法取得下载链接", withDescription: "")
                    }
                }
                self._loadView?.removeFromSuperview()
            }
        }
        
        self._loadView?.removeFromSuperview()
        let gpid = self.selectGameDict?["gpid"] as! String
        if let app = PlatformApp.getInstance(gpid){
            app.routeGame(callback)
        }else{
            self.toGamePage(dict: self.selectGameDict)
        }
    }
    //进入游戏
    func toGamePage(dict:[String:Any]?){
        let gpid = dict?["gpid"] as? String
        let accid = dict?["accid"] as? String
        DispatchQueue.main.async {
            self._loadView?.removeFromSuperview()
            self._loadView = UIHelper.initLoadView(self, withMessage: "检查账户...")
            self._loadView?.center = self.view.center
            self.view.addSubview(self._loadView!)
        }
        let title =  self.outplaformDic["f_name"] as? String ?? ""
        print("参数/kz/gp/v1/enter?id=\(gpid!) accid:\(accid!)")
        RequestHelper.post(atPath:"/kz/gp/v1/enter?id="+gpid!, withData: ["accid":accid!], withCompletion: { data in
            let responseObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] ?? [:]
            let code = responseObject["code"] as? Int ?? -1
            DispatchQueue.main.async{
                if data.count <= 0{
                    ToolHelper.statisticsPage(pageName:"\(title)-\(dict?["name"] as? String ?? "")-api_失败")
                    UIHelper.alertSimpleMessage(about: "接口数据异常。", withDescription: "", in: self)
                    self._effecView?.removeFromSuperview()
                    self._loadView?.removeFromSuperview()
                    return
                }
                if code == 0 {
                    ToolHelper.statisticsPage(pageName:"\(title)-\(dict?["name"] as? String ?? "")-api_成功")
                    var data = responseObject["data"] as? [[String:Any]]  ?? []
                    print("Check Enter:\(responseObject)")
                    if data.count <= 0 {
                        self._loadView?.removeFromSuperview()
                        self._effecView?.removeFromSuperview()
                        UIHelper.alertSimpleMessage(about: "数据异常。", withDescription: "", in: self)
                        return
                    }
                    var s = data[0]
                    if s["status"] as? Int ?? -1 == 1 {
                        let gp = data[1]
                        if gp["status"] as? Int ?? -1 == 1 {
                            if gp["c"] as? Int ?? -1 == 1 {
                                //进入游戏 上边的是徐加的结束  mt
                                if let str = (data[2]["data"] as? [String:Any])?["val"] {
                                    var zeroFlag: Bool = false
                                    if str is String {
                                        zeroFlag = ((str as? String) == "0.00")
                                    }
                                    else {
                                        zeroFlag = ((str as? Int) == 0)
                                    }
                                    //判断是否为沙巴，若是沙巴则检查NB是否为0
//                                    if (gpid == "8246252097638400") && zeroFlag {
//                                        UIHelper.alertSimpleMessage(about: "沙巴平台余额提醒", withDescription: "沙巴平台余额为0的情况下无法游戏，请先转账", in: self, withOKButton: true)
//                                        return
//                                    } else {
                                        self._loadView?.removeFromSuperview()
                                        self._loadView = UIHelper.initLoadView(self, withMessage: "进入游戏...")
                                        self._loadView?.center = self.view.center
                                        self.view.addSubview(self._loadView!)
                                        print(dict)
                                        self.pushGameViewController(dict!)
//                                    }
                                }else{
                                    
                                    UIHelper.alertSimpleMessage(about: "检查账户失败，请稍后重试。", withDescription: "", in: self)
                                    self._loadView?.removeFromSuperview()
                                    //mt20171221 添
                                    self._effecView?.removeFromSuperview()
                                }
                            }else {
                                //注册游戏
                                //                              [UIHelper displayTip:@"系统维护中，当前无法进入游戏" delay:1.5f view:self.view];
                                //checkREG(accid, url: url)
                                self.checkReg(dict!)
                            }
                        }
                        else {
                            
                            UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐", withDescription: "", in: self)
                        }
                       self._loadView?.removeFromSuperview()
                        //mt20171221 添
                        self._effecView?.removeFromSuperview()
                    }
                    else {
                        
                        let tip: String = "系统维护中(\(s["s"] as? String ?? "")-\(s["e"] as? String ?? ""))，当前无法进入游戏"
                        UIHelper.alertSimpleMessage(about: tip, withDescription: "", in: self)
                        self._loadView?.removeFromSuperview()
                        //mt20171221 添
                        self._effecView?.removeFromSuperview()
                    }
                }
                else if code == 999 || code == 1150 {
                    UIHelper.displayLoginExpireTip(self)
                    //mt20171221 添
                    UIHelper.removeEffect()
                    self._loadView?.removeFromSuperview()
                    //mt20171221 添
                    self._effecView?.removeFromSuperview()
                }
                else {
                    ToolHelper.statisticsPage(pageName:"\(title)-\(dict?["name"] as? String ?? "")-api_失败")
                    UIHelper.alertSimpleMessage(about: "发生错误: \(Int(code))", withDescription: "", in: self)
                    self._loadView?.removeFromSuperview()
                    //mt20171221 添
                    self._effecView?.removeFromSuperview()
                }
            }
            
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                ToolHelper.statisticsPage(pageName:"\(title)-\(dict?["name"] as? String ?? "")-api_失败")
                UIHelper.alertSimpleMessage(about: "检查账户失败，请稍后重试，\(getErrorString())。", withDescription: "", in: self)
                self._loadView?.removeFromSuperview()
                //mt20171221 添
                self._effecView?.removeFromSuperview()
            }
        })
    }
    
    func checkReg(_ platform: [String:Any]){
        let gpid = platform["accid"] as? String
        DispatchQueue.main.async {
            self._loadView?.removeFromSuperview()
            self._loadView = UIHelper.initLoadView(self, withMessage: "检查账号...")
            self._loadView?.center = self.view.center
            self.view.addSubview(self._loadView!)
        }
        
        RequestHelper.post(atPath: "/kz/gp/reg", withData: ["gpid":gpid!], withCompletion: { data in
            let responseObject = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            let code = responseObject["c"] as! Int
            print("reg:\(responseObject)")
            DispatchQueue.main.async {
                if code == 0 {
                    //进入游戏
                    self.pushGameViewController(platform)
                }
                else if code == 1407 {
                    //mt 20171221 add
                    self._effecView?.removeFromSuperview()
                    UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐。", withDescription: "", in: self)
                }
                else if code  == 999 || code  == 1150 {
                    //mt 20171221 add
                    self._effecView?.removeFromSuperview()
                    UIHelper.displayLoginExpireTip(self.parent!)
                }
                self._loadView?.removeFromSuperview()
                //mt 20171221 add
                self._effecView?.removeFromSuperview()
            }
            
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐。\(getErrorString())", withDescription: "", in: self)
            }
            self._loadView?.removeFromSuperview()
            //mt 20171221 add
            self._effecView?.removeFromSuperview()
        })
    }
    
    func jumpViewControllerAndCloseSelf(vc:UIViewController) ->Void{
        var viewControlles:[UIViewController] = self.navigationController?.viewControllers ?? []
//        var newviewControlles = [UIViewController]()
//        for (index,item) in 0 ... ((viewControlles?.count ?? 0) - 1){
//
//        }
        if viewControlles.count >= 2 {
            viewControlles.remove(at:viewControlles.count-1)
        }
        viewControlles.append(vc)
        self.navigationController?.setViewControllers(viewControlles, animated: true)
    }
    func pushGameViewController(_ gp: [String:Any]){
        self._loadView?.removeFromSuperview()
        if let games = gp["games"] as? [[String:Any]] {
            //Platforms with sub games
            let vc = VideoGamesVC()
            vc.platform = gp
            vc.subGameList = games
            vc.hidesBottomBarWhenPushed=true
            let orientationTarget = NSNumber(integerLiteral: UIInterfaceOrientation.portrait.rawValue)
            UIDevice.current.setValue(orientationTarget, forKey: "orientation")
            self.jumpViewControllerAndCloseSelf(vc: vc)
          //  self.navigationController?.pushViewController(vc, animated: true)
          //  self.navigationController?.viewControllers.remove(at: (self.navigationController?.viewControllers.count)! - 2)
        }else{
            if let useWK = gp["use_WK"] as? Bool {
                if useWK == false {
                    let goNext = GameWebViewController.instanceFromStoryboard()!
             //       let goNext = GameWebViewController()
                    goNext.gpid = gp["gpid"] as? String
                    goNext.url = gp["url"] as? String
                    goNext.hidesBottomBarWhenPushed = true
                   // self.navigationController?.pushViewController(goNext, animated: true)
                   // self.navigationController?.viewControllers.remove(at: (self.navigationController?.viewControllers.count)! - 2)
                    self.jumpViewControllerAndCloseSelf(vc: goNext)
                    
                }else{
                    let goNext = GameWKWebViewController.instanceFromStoryboard()!
                    
                    goNext.gpid = gp["gpid"] as? String
                    goNext.url = gp["url"] as? String
                    goNext.hidesBottomBarWhenPushed = true
                    self.jumpViewControllerAndCloseSelf(vc: goNext)
                 //   self.navigationController?.pushViewController(goNext, animated: true)
                 //    self.navigationController?.viewControllers.remove(at: (self.navigationController?.viewControllers.count)! - 2)
                }
            }
        }
    }
    
    func continueWithHTML(platform:[String:Any]?){
        
        let isMaintain = platform?["status"] as? Int ?? 0
        
        if UserHelper.getLoginStatus() {
            //mt
            self._effecView?.removeFromSuperview()
            self.gameAlertView?.dismiss(animated: true)
            if isMaintain == 0 {
                UIHelper.alertSimpleMessage(about: "此游戏平台正在维护", withDescription: "", in: self)
                return
            }
            self._effecView=UIHelper.showBlurEffect(isClick:false)
            self.view.addSubview(self._effecView!)
            self._loadView = UIHelper.initLoadView(self, withMessage: "自动转入余额")
            self.view.addSubview(self._loadView!)
            let title =  self.outplaformDic["f_name"] as? String ?? ""
            RequestHelper.post(atPath: "/kz/gp/onekeyri", withData: ["toid":platform!["accid"] as! String], withCompletion: { data in
                // RequestHelper.post(atPath: "/kz/gp/onekeyri", withData: ["toid":"61005672349800"], withCompletion: { data in
                let responseObject = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
                print("一键转入:\(responseObject)")
                let code = responseObject["c"] as! Int
                
                if code == 0 {
                    
                    self.toGamePage(dict: platform)
                }
                else if code == 999 || code == 1150 {
                    //mt 20171221
                    UIHelper.removeEffect()
                    UIHelper.displayLoginExpireTip(self)
                    
                    ToolHelper.statisticsPage(pageName:"\(title)-\(platform?["name"] as? String ?? "")-api_失败")
                }
                else {
                    DispatchQueue.main.async {
                        ToolHelper.statisticsPage(pageName:"\(title)-\(platform?["name"] as? String ?? "")-api_失败")
                        UIHelper.alertSimpleMessage(about: "发生错误: \(code)", withDescription: "", in: self)
                        //mt 20171221
                        self._loadView?.removeFromSuperview()
                        self._effecView?.removeFromSuperview()
                    }
                }
            }, withError: { error in
                print(error)
                DispatchQueue.main.async {
                    ToolHelper.statisticsPage(pageName:"\(title)-\(platform?["name"] as? String ?? "")-api_失败")
                    UIHelper.alertSimpleMessage(about: "发生错误，请联系客服协助处理，\(getErrorString())", withDescription: "", in: self)
                    //mt 20171221
                    self._loadView?.removeFromSuperview()
                    self._effecView?.removeFromSuperview()
                }
            })
        }else{
            //    UIHelper.showRequireLoginTip(self) //已修改
            self.gameAlertView?.didTappedOnBackgroundView()
            LoginViewController.loginIfNeedController(currentController: self) {}
        }
    }
    //2.0进入游戏平台
    func continueWithGamePlatform(platform:[String:Any]?){
        let isMaintain = platform?["status"] as? Int ?? 0
               
        if UserHelper.getLoginStatus() {
            //mt
            self._effecView?.removeFromSuperview()
            self.gameAlertView?.dismiss(animated: true)
            if isMaintain == 0 {
                UIHelper.alertSimpleMessage(about: "此游戏平台正在维护", withDescription: "", in: self)
                return
            }
            self._effecView=UIHelper.showBlurEffect(isClick:false)
            self.parent?.parent?.view.addSubview(self._effecView!)
     //       self.view.addSubview(self._effecView!)
            self._loadView = UIHelper.initLoadView(self, withMessage: "进入游戏中...")
    //        self.view.addSubview(self._loadView!)
            self.parent?.parent?.view.addSubview(self._loadView!)
            let title =  self.outplaformDic["f_name"] as? String ?? ""
            NetWorkRequest(API.goInGamePlatform(url: "04976c8", gpid: platform!["gpid"] as? String ?? ""), completion: { (responseData,statusCode,strData) -> (Void) in
                 DispatchQueue.main.async {
                    self._loadView?.removeFromSuperview()
                    self._effecView?.removeFromSuperview()
                     let dataDict = responseData["data"].dictionary
                     let onekeyriResponse = dataDict?["onekeyriResponse"]?.dictionary
                     let enterGameResponse = dataDict?["enterGameResponse"]?.dictionary
                    let oresponse = onekeyriResponse?["response"]?.dictionary
                    let code = oresponse?["c"]?.int  ?? -1
                    if code == 0 {
                      //  self.toGamePage(dict: platform)
                     let ecode =  enterGameResponse?["code"]?.int ?? -1
                        if ecode == 0{
                           ToolHelper.statisticsPage(pageName:"\(title)-\(platform?["name"] as? String ?? "")-api_成功")
                            let data = enterGameResponse?["data"]?.array
                            if data?.count ?? 0 <= 0 {
                                 UIHelper.alertSimpleMessage(about: "数据异常。", withDescription: "", in: self)
                                return
                            }
                            //获取数组第一个的数据
                            let s = data?[0].dictionaryObject
                            if s?["status"] as? Int ?? -1 == 1 {
                                let gp = data?[1].dictionaryObject
                                if gp?["status"] as? Int ?? -1 == 1 {
                                    if gp?["c"] as? Int ?? -1 == 1  || gp?["c"] as? Int ?? -1 == 0{
                                     let dict = data?[2].dictionaryObject
                                        if let str = (dict?["data"] as? [String:Any])?["val"] {
                                            var zeroFlag: Bool = false
                                            if str is String {
                                                zeroFlag = ((str as? String) == "0.00")
                                            }else {
                                                zeroFlag = ((str as? Int) == 0)
                                            }
                                            //判断是否为沙巴，若是沙巴则检查NB是否为0
//                                            if (platform!["gpid"] as? String ?? "" == "8246252097638400") && zeroFlag {
//                                                UIHelper.alertSimpleMessage(about: "沙巴平台余额提醒", withDescription: "沙巴平台余额为0的情况下无法游戏，请先转账", in: self, withOKButton: true)
//                                                return
//                                            } else {
                                                //进入游戏
                                                self.pushGameViewController(platform!)
//                                            }
                                        }else{
                                            UIHelper.alertSimpleMessage(about: "检查账户失败，请稍后重试。", withDescription: "", in: self)
                                        }
                                    }else{
                                        //注册游戏
                                        print("注册游戏")
                                        UIHelper.alertSimpleMessage(about: "注册游戏失败，请稍后重试。", withDescription: "", in: self)
                                     //    self.checkReg(platform!)
                                    }
                                }else{
                                    UIHelper.alertSimpleMessage(about: "系统维护中，当前无法进入游戏，在此期间建议您选择其它万博游戏平台娱乐", withDescription: "", in: self)
                                }
                            }else{
                                let tip: String = "系统维护中(\(s?["s"] as? String ?? "")-\(s?["e"] as? String ?? ""))，当前无法进入游戏"
                                UIHelper.alertSimpleMessage(about: tip, withDescription: "", in: self)
                            }
                        }else if code == 999 || code == 1150 {
                            //mt 20171221
                            UIHelper.removeEffect()
                            LoginViewController.loginIfNeedController(currentController: self) {}
                            ToolHelper.statisticsPage(pageName:"\(title)-\(platform?["name"] as? String ?? "")-api_失败")
                        }else{
                            ToolHelper.statisticsPage(pageName:"\(title)-\(platform?["name"] as? String ?? "")-api_失败")
                            UIHelper.alertSimpleMessage(about: "发生错误: \(Int(code)) \(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                        }
                    }else if code == 999 || code == 1150 {
                        //mt 20171221
                        UIHelper.removeEffect()
                        LoginViewController.loginIfNeedController(currentController: self) {}
                        ToolHelper.statisticsPage(pageName:"\(title)-\(platform?["name"] as? String ?? "")-api_失败")
                    }else{
                        ToolHelper.statisticsPage(pageName:"\(title)-\(platform?["name"] as? String ?? "")-api_失败")
                         UIHelper.alertSimpleMessage(about: "发生错误: \(Int(code)) \(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                    }
                }
            }, failed: { (faildInfo,reCode,msg) -> (Void) in
                DispatchQueue.main.async {
                    ToolHelper.statisticsPage(pageName:"\(title)-\(platform?["name"] as? String ?? "")-api_失败")
                    if reCode == "21002"{
                        LoginViewController.loginIfNeedController(currentController: self) {}
                    }else{
                        UIHelper.alertSimpleMessage(about: "发生错误: \(Int(reCode)) \(CodeMessageHelper.get(String(reCode)))", withDescription: "", in: self)
                    }
    
                    self._loadView?.removeFromSuperview()
                    self._effecView?.removeFromSuperview()
                }
            }) { () -> (Void) in
                DispatchQueue.main.async {
                        ToolHelper.statisticsPage(pageName:"\(title)-\(platform?["name"] as? String ?? "")-api_失败")
                        UIHelper.alertSimpleMessage(about: "发生错误，请联系客服协助处理，\(getErrorString())", withDescription: "", in: self)
                        //mt 20171221
                        self._loadView?.removeFromSuperview()
                        self._effecView?.removeFromSuperview()
                }
            }
        }else{
            self.gameAlertView?.didTappedOnBackgroundView()
            LoginViewController.loginIfNeedController(currentController: self) {}
        }
    }
    
    // 导航栏左边按钮
    func leftButtonActionWithImg(_ image: String) {
        let naviLeftButton = UIButton.init(type: UIButton.ButtonType.custom)
        naviLeftButton.frame = CGRect.init(x: 0, y: 0, width: 22, height: 22);
        naviLeftButton.setBackgroundImage(UIImage.init(named: image), for: UIControl.State.normal)
        naviLeftButton.setBackgroundImage(UIImage.init(named: image), for: UIControl.State.highlighted)
        naviLeftButton.addTarget(self, action: #selector(doLeftNaviAction), for: UIControl.Event.touchUpInside)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: naviLeftButton)
    }
    // 导航栏左边按钮点击
    @objc func doLeftNaviAction() {
        self.navigationController?.popViewController(animated: true)
    }
}
